#include <stdio.h>

void strcpy(char*, char*);
int strcmp(char*, char*);
void strcat(char*, char*);
int strend(char*, char*);
void strcpy(char*, char*, int);
void strcat(char*, char*, int);
int strcmp(char*, char*, int);

int main() {
	char a[13];
	char b[13] = "hello, world";

	printf("compare a with b: %d\n", strcmp(a, b));
	strcpy(a, b);
	printf("a: %s, b: %s\n", a, b);

	char c[] = "hello, kugou";

	printf("compare a with b: %d\n", strcmp(a, b));
	printf("compare b with c: %d\n", strcmp(c, b));

	char d[23] = "Iron Man: ";

	strcat(d, b);
	printf("%s\n", d);

	char e[] = "hello world";
	char f[] = "world";
	char g[] = "worl";

	printf("f in e end: %d\n", strend(e, f));
	printf("g in e end: %d\n", strend(e, g));

	char h[6];
	char j[20];
	char i[] = "hello, world";

	strcpy(h, i, 5);
	printf("h: %s\n", h);
	strcpy(j, i, 15);
	printf("j: %s\n", j);

	char k[20] = "spider man: ";
	char l[] = "hello sir!";

	strcat(k, l, 7);
	printf("k: %s\n", k);

	char m[] = "hello";
	char n[] = "hellp";

	printf("compare m with n: %d\n", strcmp(m, n, 4));
	printf("compare m with n: %d\n", strcmp(m, n));

	return 0;
}

void strcpy(char* a, char* b) {
	while (*(a++) = *(b++));
}

int strcmp(char* a, char* b) {
	while (*a++ == *b++)
	{
		if (!*a) return 0;
	}
	a--;
	b--;
	return *a - *b;
}

void strcat(char* a, char* b) {
	while (*a++ != '\0');
	a--;
	while (*a++ = *b++);
}

int strend(char* a, char* b) {
	int n = 0;

	for (; *a; a++)
	{
		if (*a == *b) {
			n++;
			b++;
		}
		else {
			b -= n;
			n = 0;
		}
	}
	if (!*b) {
		return 1;
	}
	else {
		return 0;
	}
}

void strcpy(char* a, char* b, int max) {
	while ((*a++ = *b++) && --max);
	if (*b) *a = '\0';
}

void strcat(char* a, char* b, int max) {
	while (*a++ != '\0');
	a--;
	while ((*a++ = *b++) && --max);
	if (*b) *a = '\0';
}

int strcmp(char* a, char* b, int max) {
	while ((*a++ == *b++) && --max)
	{
		if (!*a) return 0;
	}
	a--;
	b--;
	if (!max) {
		return 0;
	}
	else {
		return *a - *b;
	}
}